package service

import (
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
)

type CoachService interface {
	Create(req *model.CoachCreateReq) error
	Update(id uint, req *model.CoachUpdateReq) error
	Delete(id uint) error
	GetByID(id uint) (*model.Coach, error)
	List(page, pageSize int) ([]model.Coach, int64, error)
}

type coachService struct {
	repo repository.CoachRepository
}

func NewCoachService(repo repository.CoachRepository) CoachService {
	return &coachService{repo: repo}
}

func (s *coachService) Create(req *model.CoachCreateReq) error {
	// 检查手机号是否已存在
	if existing, _ := s.repo.GetByPhone(req.Phone); existing != nil {
		return errors.New("手机号已存在")
	}

	coach := &model.Coach{
		Name:        req.Name,
		Phone:       req.Phone,
		Email:       req.Email,
		Gender:      req.Gender,
		Specialty:   req.Specialty,
		Experience:  req.Experience,
		Certificate: req.Certificate,
		Status:      1,
	}

	return s.repo.Create(coach)
}

func (s *coachService) Update(id uint, req *model.CoachUpdateReq) error {
	coach, err := s.repo.GetByID(id)
	if err != nil {
		return errors.New("教练不存在")
	}

	if req.Name != "" {
		coach.Name = req.Name
	}
	if req.Email != "" {
		coach.Email = req.Email
	}
	if req.Gender != "" {
		coach.Gender = req.Gender
	}
	if req.Specialty != "" {
		coach.Specialty = req.Specialty
	}
	if req.Experience != nil {
		coach.Experience = *req.Experience
	}
	if req.Certificate != "" {
		coach.Certificate = req.Certificate
	}
	if req.Status != nil {
		coach.Status = *req.Status
	}

	return s.repo.Update(coach)
}

func (s *coachService) Delete(id uint) error {
	if _, err := s.repo.GetByID(id); err != nil {
		return errors.New("教练不存在")
	}
	return s.repo.Delete(id)
}

func (s *coachService) GetByID(id uint) (*model.Coach, error) {
	return s.repo.GetByID(id)
}

func (s *coachService) List(page, pageSize int) ([]model.Coach, int64, error) {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	return s.repo.List(page, pageSize)
}
